package com.coffeeloversupportlibrary.coffeelover.mercury.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.renderscript.RenderScript;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

import java.security.MessageDigest;

import jp.wasabeef.glide.transformations.internal.FastBlur;

/**
 * @author 盛守义
 * @createTime 2021/11/13 11:22
 * @projectName TurningCoffee
 * @className BlurTransformation.java
 * @description TODO
 */
public class BlurTransformation extends BitmapTransformation {
    private static final int VERSION = 1;
    private static final String ID = "BlurTransformation." + VERSION;

    private static int MAX_RADIU = 25;
    private static int DEFAULT_DOWN_SAMPLING = 1;

    private int radius;
    private int sampling;

    public BlurTransformation(){
        this(MAX_RADIU, DEFAULT_DOWN_SAMPLING);
    }

    public BlurTransformation(int radius){
        this(radius, DEFAULT_DOWN_SAMPLING);
    }

    public BlurTransformation(int radius, int sampling){
        this.radius = radius;
        this.sampling = sampling;
    }

    @Override
    protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
        int width = toTransform.getWidth();
        int height = toTransform.getHeight();
        int scaleWidth = width/sampling;
        int scaleHeight = height/sampling;

        Bitmap bitmap = pool.get(scaleWidth, scaleHeight, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        canvas.scale(1/(float)sampling, 1/(float)sampling);
        Paint paint = new Paint();
        paint.setFlags(Paint.FILTER_BITMAP_FLAG);
        canvas.drawBitmap(toTransform, 0,0, paint);
        bitmap = FastBlur.blur(bitmap, radius, true);

        return bitmap;
    }

    @Override
    public int hashCode() {
        return ID.hashCode() + radius*1000 + sampling * 10;
    }

    @Override
    public boolean equals(@Nullable Object obj) {
        return obj instanceof BlurTransformation&&
                ((BlurTransformation)obj).radius == radius&&
                ((BlurTransformation)obj).sampling == sampling;
    }

    @NonNull
    @Override
    public String toString() {
        return "BlurTransformation(radius=" + radius + ", sampling=" + sampling + ")";
    }

    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
        messageDigest.update((ID + radius + sampling).getBytes(CHARSET));
    }
}
